import React, { useState, createContext, useEffect } from "react";
import "../../index.less";
import less from "less";
import { ThemeSwitch } from "./ThemeSwitch";

export type Theme = "light" | "dark";

export const ThemeContext = createContext<{
  theme: Theme;
  toggleTheme: (theme: Theme) => void;
}>(null!);

export function ThemeProvider() {
  const [theme, setTheme] = useState<Theme>(
    (localStorage.getItem("theme") as Theme) || "light"
  );

  const updateLessVars = async () => {
    try {
      console.log("Updating LESS variables...");
      await less.modifyVars({
        "@primary-color": theme === "light" ? "#029cfd" : "#9b1f25", // 使用标准颜色格式
      });
      console.log("LESS variables updated successfully.");
    } catch (error) {
      console.error("Failed to update LESS variables:", error);
    }
  };

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    updateLessVars();
    localStorage.setItem("theme", theme);
  }, [theme]);

  return (
    <ThemeContext.Provider
      value={{
        theme,
        toggleTheme: (val) => setTheme(val),
      }}
    >
      <ThemeSwitch />
    </ThemeContext.Provider>
  );
}
